
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

import java.util.logging.Logger;

/**
 * @program: LearShiro-1
 * @description:
 * @author: Mr.Dai
 * @create: 2020-03-12 22:51
 **/
public class TestShiro {

    private final  static Logger log=Logger.getLogger(TestShiro.class.getName());

    public static void main(String[] args) {
        log.info("My First Apache Shiro Application");
        //DefaultEnvironment environment = new DefaultEnvironment();
        // 加载ini 配置文件 创建 Security Manager factory
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        //将SecurityManager托管到SecurityUtils工具类中（ops：之后可以不必关心SecurityManager）
        SecurityUtils.setSecurityManager(securityManager);

        //获得Subject，通过subject可以执行shiro的相关功能操作（身份认证或权限校验等）
        Subject currentUser = SecurityUtils.getSubject();

        // 身份登录逻辑
        if(!currentUser.isAuthenticated()){
            //如果未登录，则封装一个token，其中包含用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","123");
            token.setRememberMe(true);
            try {
                //将token传入Login方法，进行身份认证（判断用户名和密码是否正确）
                currentUser.login(token);
                //如果失败则会抛出异常
            }catch (UnknownAccountException e){
                // 用户不存在
                log.info("There is no user with username of " + token.getPrincipal());
            }catch (IncorrectCredentialsException  e){
                // 用户密码错误
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            }catch (LockedAccountException e){
                // 用户账户冻结
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }// 其他 认证异常
            catch (AuthenticationException e) {
                e.printStackTrace();
                log.info("There is no user with username of " + token.getPrincipal());
            }
        }
        System.out.println(currentUser.isAuthenticated());
        //认证成功则用户信息会存入currentUser（Subject）
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        // 校验角色
        if (currentUser.hasRole("admin")){
            log.info(currentUser.getPrincipal()+" 具有admin权限");
        }else {
            log.info(currentUser.getPrincipal()+" 不具有admin权限");
        }
        // 校验权限
        if (currentUser.isPermitted("user:insert")){
            log.info(currentUser.getPrincipal()+" 具有user:insert权限");
        }else {
            log.info(currentUser.getPrincipal()+" 不具有user:insert权限");
        }
        // 会话使用
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }
        // 清楚状态
        currentUser.logout();
    }
}
